<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Comment;
use App\Models\Material;
use App\Models\Service;
use App\Models\Star;
use App\Models\User;
use App\Models\Work;
use App\Services\NotifyService;
use Dingo\Api\Http\Request;

class StarController extends BaseController
{

    public $model = Star::class;

    /**
     * 评论
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function store(Request $request) {
        $this->validate($request, [
            'entity_id' => 'required',
            'type' => 'required|in:1,2,3'
        ]);
        $user = $this->getUser();
        $input = $request->input();

        return \DB::transaction(function () use($input, $user){
            if ($input['type'] == Comment::TYPE_WORK) {
                $entity_model = new Work();
            } else if ($input['type'] == Comment::TYPE_MATERIAL){
                $entity_model = new Material();
            } else {
                $entity_model = new Service();
            }
            $entity_result = $entity_model->find($input['entity_id']);
            if (!$entity_result)
                return $this->failed("ID对应数据不存在");

            $input['user_id'] = $user->id;
            $input['entity_user_id'] = $entity_result->user_id ?? 0;

            $one = (new $this->model)->where('user_id', $user->id)->where('entity_id', $input['entity_id'])
                ->where('type', $input['type'])->first();
            if ($one) {
                $one->delete();
                $star = 'cancel';

            } else {
                $this->model::create($input);
                $star = 'ok';
                $input['entity_user_id'] && NotifyService::store($input['user_id'], 1, $input['entity_id'], $input['entity_user_id'], '', $input['type']);
            }
            $num = ($star == 'ok' ? 1 : -1);

            //当前用户自己点赞数增减
            $user->increment('star_count', $num);
            //被点赞用户 点赞数增减
            if ($input['entity_user_id']) {
                $stared = User::find($input['entity_user_id']);
                $stared->increment('stared_count', $num);
            }
            $entity_result->increment('star_num', $num);
            return $this->success([
                'star' => $star
            ]);
        });
    }

}

